/**
 * @Title: CartServiceImpl
 * @Package cn.com.yiqi.wsc.service.customer.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/2/23 11:53
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.customer.impl;

import cn.com.yiqi.wsc.Ro.CartVO;

import cn.com.yiqi.wsc.Ro.OrderDetailVo;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.customer.CartMapper;

import java.math.BigDecimal;
import java.util.*;

import cn.com.yiqi.wsc.dao.order.OrderMainMapper;
import cn.com.yiqi.wsc.dao.shop.ItemMapper;
import cn.com.yiqi.wsc.entity.customer.Cart;
import cn.com.yiqi.wsc.entity.customer.CartExample;
import cn.com.yiqi.wsc.entity.customer.Customer;

import cn.com.yiqi.wsc.entity.shop.Item;
import cn.com.yiqi.wsc.enumeration.ItemStatusEnum;
import cn.com.yiqi.wsc.service.file.dataobject.QiniuConfig;
import cn.com.yiqi.wsc.service.item.enumerate.ItemKindEnum;
import cn.com.yiqi.wsc.service.order.impl.OrderServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 *@ClassName: CartServiceImpl
 * Description: TODO
 * @author 会员系统组-林威
 * @date 2017/2/23 11:53
 *
 */
@Service
public class CartServiceImpl {
    @Autowired
    CartMapper cartDao;

    @Autowired
    OrderServiceImpl orderService;

    @Autowired
    OrderMainMapper orderDao;
    
    @Autowired
    QiniuConfig qiniuConfig;

    @Autowired
    ItemMapper itemdao;
    /**获取购物车内容
     * */
    public List<CartVO> findAll(Integer userId) {
        return cartDao.findItemInfo(userId);
    }

    @Transactional
    public Integer adjustCount(Integer id, Integer count) {
        Cart cart = cartDao.selectByPrimaryKey(id);
        cart.setCount(count);
        cartDao.updateByPrimaryKeySelective(cart);
        return count;
    }

    /**加入购物车*/
    @Transactional
    public void addToCart(Integer userId, Integer itemId) {
        Item item = itemdao.selectByPrimaryKey(itemId);
        if(item.getKind() != ItemKindEnum.item.getValue() || item.getStatus() != ItemStatusEnum.上架.getValue().byteValue()){
           //vip  和 积分商品不能加入购物车
            return;
        }
        Cart cart = cartDao.findByItemIdAndUserId(userId,itemId);

        if(cart != null ){
            cart.setCount(cart.getCount()+1);
            cartDao.updateByPrimaryKeySelective(cart);
        }else {
            cart = new Cart();
            cart.setCount(1);
            cart.setCustomerId(userId);
            cart.setItemId(itemId);
            cart.setAddTime(new Date());
            cartDao.insertSelective(cart);
            //cartLog新增记录
            cartDao.insertLog(userId,2,itemId);
        }
    }

    /**
     * 从购物车中删除
     * */
    @Transactional
    public void deleteFromCart(Integer id, Integer userId) {
        Cart cart = cartDao.selectByPrimaryKey(id);
        if(cart != null && cart.getCustomerId() == userId){
            //cartLog删除记录
            cartDao.insertLog(userId,1,cart.getItemId());
            //删除购物车
            cartDao.deleteByPrimaryKey(cart.getId());
        }
    }

    /**
     * 清空购物车
     * */
    @Transactional
    public void clearCart(Integer userId) {

        List<Cart> list = cartDao.findbyUserId(userId);
        for (int i = 0; i < list.size(); i++) {
            //cartLog删除记录
            cartDao.insertLog(userId,1,list.get(i).getItemId());
            //删除购物车
            cartDao.deleteByPrimaryKey(list.get(i).getId());
        }
    }

    /**
     * 结算购物车
     * */
    public Result<Customer> calCart(Integer userId) {
        Result re = new Result();
        BigDecimal amount = BigDecimal.ZERO;
        List<CartVO> cart = findAll(userId);
        if(cart == null || cart.size() ==0 ){
            return ResultUtil.fail(re,"购物车没有商品");
        }
        //商家id，订单详情Vo
        Map<Integer,OrderDetailVo>  map = new HashMap<>();
        for (CartVO c:cart){
            //订单总额
            amount = amount.add(c.getPrice().multiply(new BigDecimal(c.getCount()+"")));
            if(map.keySet().contains(c.getOrgId())){
                OrderDetailVo vo = map.get(c.getOrgId());
                vo.getItems().add(c);
                vo.setTotalPrice(vo.getTotalPrice().add(c.getPrice().multiply(new BigDecimal(c.getCount()+""))));
                continue;
            }
            OrderDetailVo orderDetail = new OrderDetailVo();
            orderDetail.setUserId(userId);
            orderDetail.setOrgId(c.getOrgId());
            orderDetail.setTotalPrice(c.getPrice().multiply(new BigDecimal(""+c.getCount())));
            orderDetail.setShopName(c.getOrgName());
            List items = new ArrayList();
            items.add(c);
            c.setItemUrl(qiniuConfig.getURL()+"/"+c.getItemUrl());
            orderDetail.setItems(items);
            map.put(c.getOrgId(),orderDetail);
        }
        List<OrderDetailVo> list1 = new ArrayList<>(map.values());
        re.putData("list",list1);
        re.putData("total",amount);
        return re;
    }


    /**
     * 去付款
     * */
    @Transactional
    public Result pay(Integer userId,Integer addressId) {
        Result re = new Result();
        //查询用户购物车详情
        List<CartVO> cart = findAll(userId);
        if(cart == null || cart.size() ==0 ){
            return ResultUtil.fail(re,"购物车没有商品！");
        }

        BigDecimal amount = BigDecimal.ZERO;

        //商家id，订单详情Vo
        Map<Integer,OrderDetailVo>  map = new HashMap<>();
        for (CartVO c:cart){
            //订单总额
            amount = amount.add(c.getPrice().multiply(new BigDecimal(""+c.getCount())));
            if(map.keySet().contains(c.getOrgId())){
                OrderDetailVo vo = map.get(c.getOrgId());
                vo.getItems().add(c);
                vo.setTotalPrice(vo.getTotalPrice().add(c.getPrice().multiply(new BigDecimal(""+c.getCount()))));
                continue;
            }
            OrderDetailVo orderDetail = new OrderDetailVo();
            //orderDetail.setUserId(userId);
            orderDetail.setOrgId(c.getOrgId());
            orderDetail.setTotalPrice(c.getPrice().multiply(new BigDecimal(""+c.getCount())));
            //orderDetail.setShopName(c.getOrgName());
            List items = new ArrayList();
            items.add(c);
            orderDetail.setItems(items);
            //TODO 设置发货地址
            map.put(c.getOrgId(),orderDetail);
        }
        List<OrderDetailVo> list1 = new ArrayList<>(map.values());
        // 子订单以及订单对应商品
        re = orderService.createOrder(userId,list1,amount,addressId);
        if(!ResultUtil.isSuccess(re)){
            return re;
        }

        // 调用清空购物车
        cartDao.deleteUserCart(userId);
        return re;
    }


    /**
     * 计算购物车总价
     * */
    public BigDecimal calCartTOtal(Integer userId) {
        return cartDao.calTotalByuserId(userId);
    }
}
